#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <vector>
#include <functional>
#include <future>
#include <memory>
#include <atomic>

class ThreadPool {
private:
    // Worker线程列表
    std::vector<std::thread> workers;
    
    // 任务队列
    std::queue<std::function<void()>> tasks;
    
    // 同步原语
    std::mutex queue_mutex;
    std::condition_variable condition;
    
    // 线程池状态
    std::atomic<bool> stop_flag{false};

public:
    // 构造函数：初始化指定数量的线程
    explicit ThreadPool(size_t thread_count = std::thread::hardware_concurrency()) {
        for (size_t i = 0; i < thread_count; ++i) {
            workers.emplace_back([this] {
                for (;;) {
                    std::function<void()> task;
                    
                    {
                        std::unique_lock<std::mutex> lock(this->queue_mutex);
                        this->condition.wait(lock, [this] { 
                            return this->stop_flag || !this->tasks.empty(); 
                        });
                        
                        if (this->stop_flag && this->tasks.empty()) {
                            return;
                        }
                        
                        task = std::move(this->tasks.front());
                        this->tasks.pop();
                    }
                    
                    task();
                }
            });
        }
    }
    
    // 禁止拷贝
    ThreadPool(const ThreadPool&) = delete;
    ThreadPool& operator=(const ThreadPool&) = delete;
    
    // 提交任务模板函数
    template<class F, class... Args>
    auto submit(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type> {
        using return_type = typename std::result_of<F(Args...)>::type;
        
        auto task = std::make_shared<std::packaged_task<return_type()>>(
            std::bind(std::forward<F>(f), std::forward<Args>(args)...)
        );
        
        std::future<return_type> res = task->get_future();
        
        {
            std::unique_lock<std::mutex> lock(queue_mutex);
            
            // 如果线程池已停止，则拒绝新任务
            if (stop_flag) {
                throw std::runtime_error("submit on stopped ThreadPool");
            }
            
            tasks.emplace([task](){ (*task)(); });
        }
        
        condition.notify_one();
        return res;
    }
    
    // 析构函数：清理所有线程
    ~ThreadPool() {
        {
            std::unique_lock<std::mutex> lock(queue_mutex);
            stop_flag = true;
        }
        
        condition.notify_all();
        
        for (std::thread &worker : workers) {
            if (worker.joinable()) {
                worker.join();
            }
        }
    }
    
    // 获取线程池大小
    size_t size() const {
        return workers.size();
    }
    
    // 检查是否有空闲线程
    bool busy() const {
        std::unique_lock<std::mutex> lock(queue_mutex);
        return !tasks.empty();
    }
};

// 使用示例
int main() {
    // 创建一个具有默认线程数的线程池
    ThreadPool pool;
    
    std::cout << "Thread pool created with " << pool.size() << " threads\n";
    
    // 提交一些任务
    std::vector<std::future<int>> results;
    
    for (int i = 0; i < 8; ++i) {
        results.emplace_back(
            pool.submit([i] {
                std::this_thread::sleep_for(std::chrono::milliseconds(100 * (i+1)));
                return i * i;
            })
        );
    }
    
    // 获取结果
    for (auto && result : results) {
        std::cout << "Result: " << result.get() << std::endl;
    }
    
    return 0;
}